# -*- coding: utf-8 -*-
'''
Created on 2016年8月17日

@author: huanghaoyu
'''

import os
import sys
sys.path.append(os.path.abspath('%s/../../../..' % sys.path[0]))  # 在命令行中运行时需要加入路径

import time
from com.unitoll.test.data.excel_struct import ExcelStruct
from com.unitoll.test.main.testing import test_businesses
import threading

EXCEL_FILE = os.getcwd() + "/resources/" + "testData.xlsx"

# 所有业务
ALL_BIZ_NAMES = ('PLAT', 'RDCD', 'RDTN', 'CKCD', 'PURC', 'LOAD', 'LOCK', 'UNLK', 'RDAC', 'RDIM', 'WRAC', 'WRIM')

# 要测试的业务子集
BIZ_NAMES = ('PLAT',)

EXCEL_STRUCTS = []

TOTAL_TIME = 0.0
ERROR_NUM = 0;
MUTEX = threading.Lock()

THREAD_NUM = 1
QNUM = 1

def init():
    for biz_name in BIZ_NAMES:
        excel_struct = ExcelStruct(EXCEL_FILE, biz_name)
        EXCEL_STRUCTS.append(excel_struct)
    
class TestThread(threading.Thread):
    def __init__(self, thread_id):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
    
    def run(self):
        global ERROR_NUM, TOTAL_TIME, MUTEX, QNUM
        for i in range(QNUM):
            try:
                start = time.clock()
                is_passed = test_businesses(EXCEL_STRUCTS)
                end = time.clock()
                if is_passed is True:
                    print "Thread %d tests passed.\n" % self.thread_id
                    if MUTEX.acquire(1) == True:
                        TOTAL_TIME = TOTAL_TIME + end - start
                        MUTEX.release()
                else:
                    print "Warning: Thread %d tests not passed.\n" % self.thread_id
                    if MUTEX.acquire(1) == True:
                        ERROR_NUM = ERROR_NUM + 1
                        MUTEX.release()
            except Exception, e:
                if MUTEX.acquire(1) == True:
                    ERROR_NUM = ERROR_NUM + 1
                    MUTEX.release()

if __name__ == '__main__':
    global THREAD_NUM
     
    init()
    threads = []
     
    for i in range(THREAD_NUM):
        thread = TestThread(i)
        thread.start()
        threads.append(thread)
     
    for t in threads:
        t.join()
         
    print "Testing thread number: %d" % THREAD_NUM
    print "Error ratio: %f percent" % (ERROR_NUM/(THREAD_NUM*QNUM)*100)
    if TOTAL_TIME != 0.0:
        print "Total time: %f seconds" % TOTAL_TIME
        print "Average time: %f seconds" % (TOTAL_TIME / (THREAD_NUM * QNUM))
    print "Exiting main thread."
    raw_input("Press any key to exit...")
     
